package com.kun.web.controller.activiti;

import com.kun.dto.ProcessInstanceDto;
import com.kun.service.service.IProcessInstanceService;
import com.kun.utils.AjaxResult;
import com.kun.vo.ProcessInstanceVo;
import lombok.RequiredArgsConstructor;
import org.activiti.api.model.shared.model.VariableInstance;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.model.payloads.*;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;

@RestController
@RequestMapping("/process-instance")
@RequiredArgsConstructor
public class ProcessInstanceController {

    private final IProcessInstanceService processInstanceService;
    private final ProcessRuntime processRuntime;

    /**
     * 查询流程实例 / 正在进行的或已暂停
     */
    @GetMapping("/list")
    public ResponseEntity<AjaxResult> list(ProcessInstanceDto processInstance) {
        return AjaxResult.success(processInstanceService.pageList(processInstance));
    }

    /**
     * 根据流程实例ID查询
     */
    @GetMapping("/{processInstanceId}")
    public ResponseEntity<AjaxResult> getProcessById(@NotBlank(message = "实例ID不能为空") @PathVariable String processInstanceId) {
        return AjaxResult.success(processRuntime.processInstance(processInstanceId));
    }


    /**
     * 启动流程实例
     */
    @PostMapping("/start")
    public ResponseEntity<AjaxResult> startProcessInstance(@Valid @RequestBody ProcessInstanceVo processDefinition) {
        return AjaxResult.success(processInstanceService.startInstance(processDefinition.getKey(),
                processDefinition.getName()));
    }

    /**
     * 更新流程实例状态
     */
    @PutMapping("/update-status/{processInstanceId}")
    public ResponseEntity<AjaxResult> updateStatus(@NotBlank(message = "实例ID不能为空") @PathVariable
                                                   String processInstanceId) {
        return AjaxResult.success(processInstanceService.updateStatus(processInstanceId));
    }

    /**
     * 删除流程实例
     */
    @DeleteMapping("/delete/{instanceId}")
    public ResponseEntity<AjaxResult> deleteProcessInstance(@NotBlank(message = "实例ID不能为空") @PathVariable String instanceId) {
        return AjaxResult.success(processInstanceService.deleteById(instanceId));
    }

    /**
     * 查询流程实例的参数
     *
     * @param instanceId 流程实例 ID
     * @return ResponseEntity 返回查询结果
     */
    @GetMapping("/variables")
    public ResponseEntity<AjaxResult> getProcessInstanceVariables(String instanceId) {
        // 查询流程实例的参数
        GetVariablesPayload build = ProcessPayloadBuilder.variables().withProcessInstanceId(instanceId).build();
        List<VariableInstance> variables = processRuntime.variables(build);
        return AjaxResult.success(variables);
    }

}
